package juc.threadlocal;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author fangbin
 * @desc
 * @date 2020/5/20 20:01
 */
public class ThreadLocalNormalUsafeResolve {
    public static void main(String[] args) {

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for(int i=0;i<1000;i++){
            int finalI = i;
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    String date = new ThreadLocalNormalUsafeResolve().date(finalI);
                    System.out.println(date);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        executorService.shutdown();
    }

    public String date(int seconds){
        Date date = new Date(1000*seconds);
        SimpleDateFormat dateFormat = ThreadSafeFormatter .dateFormatThreadLocal.get();
        return dateFormat.format(date);
    }
    public String date( Date date ){
        SimpleDateFormat dateFormat = ThreadSafeFormatter .dateFormatThreadLocal.get();
        return dateFormat.format(date);
    }
}

class ThreadSafeFormatter{
    public static ThreadLocal<SimpleDateFormat> dateFormatThreadLocal=
            new ThreadLocal<SimpleDateFormat>(){
                @Override
                protected SimpleDateFormat initialValue() {
                    return new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
                }
            };
}
